<template>
  <div class="captcha">
    <canvas ref="captchaCanvas" class="captcha-image" @click="refreshCaptcha"></canvas>
    <input type="text" v-model="userInput" placeholder="请输入验证码">
    <button @click="verifyCaptcha">验证</button>
  </div>
</template>

<script>
export default {

  data() {
    return {
      ctx: null,
      userInput: '',
    };
  },
  mounted() {
    this.ctx = this.$refs.captchaCanvas.getContext('2d');
    this.refreshCaptcha();
  },
  methods: {
    refreshCaptcha() {
      const canvas = this.$refs.captchaCanvas;
      const ctx = this.ctx;
      const captchaText = this.generateCaptchaText();

      // 清空画布
      ctx.clearRect(0, 0, canvas.width, canvas.height);

      // 绘制验证码文本
      ctx.font = '40px Arial';
      ctx.fillStyle = '#000';
      ctx.fillText(captchaText, 10, 40);

      // 绘制干扰线
      for (let i = 0; i < 6; i++) {
        ctx.strokeStyle = this.getRandomColor();
        ctx.beginPath();
        ctx.moveTo(this.getRandomNumber(0, canvas.width), this.getRandomNumber(0, canvas.height));
        ctx.lineTo(this.getRandomNumber(0, canvas.width), this.getRandomNumber(0, canvas.height));
        ctx.stroke();
      }
    },
    generateCaptchaText() {
      // 生成随机验证码文本
      const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      let captchaText = '';
      for (let i = 0; i < 4; i++) {
        captchaText += characters.charAt(Math.floor(Math.random() * characters.length));
      }
      return captchaText;
    },
    getRandomNumber(min, max) {
      // 生成指定范围内的随机整数
      return Math.floor(Math.random() * (max - min + 1)) + min;
    },
    getRandomColor() {
      // 生成随机颜色
      return 'rgb(' + this.getRandomNumber(0, 255) + ', ' + this.getRandomNumber(0, 255) + ', ' + this.getRandomNumber(0, 255) + ')';
    },
    verifyCaptcha() {
      // 在这里进行验证码验证逻辑
      if (this.userInput === '') {
        alert('请输入验证码');
        return;
      }

      // 进行验证码验证
      const captchaText = this.$refs.captchaCanvas.textContent;
      if (this.userInput.toUpperCase() === captchaText) {
        alert('验证通过');
      } else {
        alert('验证失败，请重新输入');
        this.refreshCaptcha();
      }
    },
  },
};
</script>

<style scoped>
.captcha {
  display: flex;
  align-items: center;
}

.captcha-image {
  margin-right: 10px;
  cursor: pointer;
  width: 100px;
  height: 50px;
}
</style>
